package com.javafish.webhello;

import com.javafish.DataHandler;
import com.javafish.webhello.Bean.Media;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;

@Controller
public class IndexController {
    String charReader(HttpServletRequest request) throws IOException {
        BufferedReader br = request.getReader();

        String str, wholeStr = "";
        while((str = br.readLine()) != null){
            wholeStr += str;
        }
        System.out.println(wholeStr);
        return wholeStr;
    }
    @RequestMapping(value="/", method= RequestMethod.GET)
    public String index(ModelMap model){
        System.out.println("Http get index!" + model);
        return "index";
    }

    @RequestMapping(value="/index", method = RequestMethod.GET)
    public String indexGet(ModelMap model, HttpServletRequest request) throws IOException {
        model.addAttribute("message","get");
        System.out.println("Http Get index!" + request.getQueryString());

        Media media = new Media();
        Date date = new Date();
        System.out.println("Current time：" + date);
        media.setCreated_time(date);
        media.setMedia_id(Integer.parseInt(request.getParameter("ID")));
        media.setStatus(request.getParameter("Status"));
        media.setType(request.getParameter("Type"));

        DataHandler dataHanler = new DataHandler();
        dataHanler.saveMedia(media);
        return "success";
    }

    @RequestMapping(value="/index", method = RequestMethod.POST)
    public String indexPost(ModelMap model, HttpServletRequest request) throws IOException {
        model.addAttribute("message","post");
        System.out.println("Http post index!" + charReader(request));

        Media media = new Media();
        media.setCreated_time(new Date());
        media.setMedia_id(Integer.parseInt(request.getParameter("ID")));
        media.setStatus(request.getParameter("Status"));
        media.setType(request.getParameter("Type"));

        DataHandler dataHanler = new DataHandler();
        dataHanler.saveMedia(media);
        return "success";
    }
}
